#include "Protocol.hpp"
#include "TcpServer.hpp"
#include "Calculate.hpp"
#include "Daemon.hpp"
#include <iostream>
#include <memory>
#include <unistd.h>

using namespace Protocol;
using namespace Net_Work;
using namespace CalCulate;
string HandlerRequest(string &inbufferstream, bool *error_code)
{
      Calculate calculte;
     std::unique_ptr<Factory> factory = std::make_unique<Factory>();
     auto req = factory->BuildRequest();
     std::string total_resp_string;
     std::string message;

     while(Decode(inbufferstream, &message))
     {
         std::cout << message << "---- messge" << std::endl;
         if(!req->Deserialize(message))
         {
             std::cout << "Deserialize error" << std::endl;
            *error_code = false;
            return std::string();
         }
          std::cout << "Deserialize success" << std::endl;
         auto resp=calculte.Cal(req);
         string send_string;
          resp->Serialize(&send_string);
          send_string=Encode(send_string);
        total_resp_string += send_string;
    }
        return total_resp_string;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage : " << argv[0] << " port" << std::endl;
        return 0;
    }
    uint16_t localport = std::stoi(argv[1]);
    unique_ptr<TcpServer> svr(new TcpServer(HandlerRequest, localport));
    svr->Loop();
    return 0;
}